import React from 'react'
import { createBrowserHistory } from 'history'
import {
  Route,
  BrowserRouter,
  Navigate,
  Routes,
  useMatch,
  unstable_HistoryRouter as HistoryRouter
} from 'react-router-dom'
import { useSelector } from 'react-redux';
import { TransitionGroup, CSSTransition } from 'react-transition-group'
import { RouterConfig } from './routerConfig'
import './router.less'
import { INIT_BASIC_STATE } from '../redux/reducers/basic';

export const history = createBrowserHistory()

interface PageProps {
  token: string
  path: string
  auth: boolean
  component: React.FC<any>
}

function Page ({ path, auth, token, component: Component }: PageProps): React.ReactElement {
  const match = useMatch(path) !== null
  if (match && auth && token === '') {
    return (
      <Navigate to='/login' />
    )
  }
  return <Component />
}

function R (): React.ReactElement {
  const { token } = useSelector((state: { basic: INIT_BASIC_STATE }) => {
    return {
      token: state.basic.token
    }
  })
  return (
    <HistoryRouter history={history}>
      <div className='container'>
        <TransitionGroup>
          <CSSTransition
            timeout={300}
            classNames="page"
            key={location.pathname}
            unmountOnExit
          >
            <Routes location={location}>
              {RouterConfig.map(({ path, auth, component: Component }) => {
                return (
                  <Route key={path} path={path} element={<Page path={path} auth={auth} component={Component} token={token} />} />
                )
              })}
            </Routes>
          </CSSTransition>
        </TransitionGroup>
        <Routes>
          {RouterConfig.map(({ path }) => <Route key={path} path={path} element={<div />} />)}
          <Route path='/' element={<Navigate to='/admin' />} />
        </Routes>
      </div>
    </HistoryRouter>
  )
}

export default R
